package com.qianya.oa.websocket;

import com.qianya.oa.common.core.domain.entity.SysUser;
import com.qianya.oa.common.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Slf4j
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    /**
     * 握手之前
     *
     * @param request    request
     * @param response   response
     * @param wsHandler  handler
     * @param attributes 属性
     * @return 是否握手成功：true-成功，false-失败
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {
        ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
        ServletServerHttpResponse serverHttpResponse = (ServletServerHttpResponse) response;
        String authorization = serverHttpRequest.getServletRequest().getHeader("Sec-WebSocket-Protocol");
        if (!StringUtils.isEmpty(authorization)) {
            serverHttpResponse.getServletResponse().setHeader("Sec-WebSocket-Protocol", authorization);
        } else {
            authorization = serverHttpRequest.getServletRequest().getHeader("Sec-WebSocket-Protocol".toLowerCase());
            serverHttpResponse.getServletResponse().setHeader("Sec-WebSocket-Protocol".toLowerCase(), authorization);
        }

        if (StringUtils.isBlank(authorization)) {
            log.error("websocket未携带token");
            return false;
        }

        SysUser user = ShiroUtils.getSysUser();
        if (user == null) {
            log.error("系统未获取到token或token已失效");
            return false;
        }
        attributes.put("uid", user.getUserId());
        attributes.put("realName", user.getUserName());
        log.info("uid:【" + user.getUserId() + "】，用户:【" + user.getUserName() + "】成功握手");
        return true;
    }

    /**
     * 握手后
     *
     * @param request   request
     * @param response  response
     * @param wsHandler wsHandler
     * @param exception exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception exception) {
        log.info("握手成功");
    }
}
